/**
 * 动画组件集合
 * 使用 React Native Reanimated 和 Lottie 创建丰富的动画效果
 * 为学习应用提供视觉吸引力和用户体验提升
 */
import React, { useEffect } from 'react';
import { View, Text, StyleSheet, Dimensions } from 'react-native';
import Animated, {
  useSharedValue,
  useAnimatedStyle,
  withTiming,
  withSpring,
  withSequence,
  withDelay,
  withRepeat,
  interpolate,
  runOnJS,
  Easing
} from 'react-native-reanimated';
import { Ionicons } from '@expo/vector-icons';

const { width, height } = Dimensions.get('window');

/**
 * 成功庆祝动画组件
 * 当用户答对题目时显示的庆祝效果
 * 简化设计，移除圆球效果，保持文字在中心
 * @param {boolean} isVisible - 是否显示动画
 * @param {Function} onAnimationComplete - 动画完成回调
 */
export function SuccessAnimation({ isVisible, onAnimationComplete }) {
  // 动画值定义
  const scale = useSharedValue(0);           // 缩放值
  const opacity = useSharedValue(0);         // 透明度
  const textScale = useSharedValue(0);       // 文字缩放

  // 当 isVisible 改变时触发动画
  useEffect(() => {
    if (isVisible) {
      startSuccessAnimation();
    } else {
      resetAnimation();
    }
  }, [isVisible]);

  /**
   * 开始成功动画序列
   * 简化版本，主要显示文字动画
   */
  const startSuccessAnimation = () => {
    // 主图标动画序列
    scale.value = withSequence(
      withTiming(1.2, { duration: 200, easing: Easing.out(Easing.quad) }),
      withTiming(1, { duration: 150, easing: Easing.inOut(Easing.quad) })
    );

    opacity.value = withTiming(1, { duration: 200 });

    // 文字动画
    textScale.value = withDelay(100,
      withSequence(
        withTiming(1.3, { duration: 300, easing: Easing.out(Easing.back(1.5)) }),
        withTiming(1, { duration: 200 }, () => {
          // 动画完成后的回调
          if (onAnimationComplete) {
            runOnJS(onAnimationComplete)();
          }
        })
      )
    );
  };

  /**
   * 重置所有动画值
   */
  const resetAnimation = () => {
    scale.value = 0;
    opacity.value = 0;
    textScale.value = 0;
  };

  // 主图标动画样式
  const mainIconStyle = useAnimatedStyle(() => ({
    transform: [{ scale: scale.value }],
    opacity: opacity.value,
  }));

  // 文字动画样式
  const textStyle = useAnimatedStyle(() => ({
    transform: [{ scale: textScale.value }],
  }));

  if (!isVisible) return null;

  return (
    <View style={styles.animationContainer}>
      {/* 主成功图标 */}
      <Animated.View style={[styles.mainIcon, mainIconStyle]}>
        <Ionicons name="checkmark-circle" size={80} color="#4CAF50" />
      </Animated.View>

      {/* 成功文字 - 使用独立的动画 */}
      <Animated.View style={[styles.successText, textStyle]}>
        <Text style={styles.successTextContent}>太棒了！</Text>
      </Animated.View>
    </View>
  );
}

/**
 * 错误提示动画组件
 * 当用户答错题目时显示的动画效果
 * 简化设计，只保留摇摆和缩放效果
 * @param {boolean} isVisible - 是否显示动画
 * @param {Function} onAnimationComplete - 动画完成回调
 */
export function ErrorAnimation({ isVisible, onAnimationComplete }) {
  const translateX = useSharedValue(0);  // 水平位移
  const opacity = useSharedValue(0);     // 透明度
  const scale = useSharedValue(0);       // 缩放
  const textScale = useSharedValue(0);   // 文字缩放

  useEffect(() => {
    if (isVisible) {
      startErrorAnimation();
    } else {
      resetAnimation();
    }
  }, [isVisible]);

  /**
   * 开始错误动画序列
   * 摇摆效果表示错误
   */
  const startErrorAnimation = () => {
    opacity.value = withTiming(1, { duration: 200 });
    scale.value = withTiming(1, { duration: 200 });

    // 摇摆动画
    translateX.value = withSequence(
      withTiming(-20, { duration: 100 }),
      withTiming(20, { duration: 100 }),
      withTiming(-15, { duration: 100 }),
      withTiming(15, { duration: 100 }),
      withTiming(0, { duration: 100 })
    );

    // 文字动画
    textScale.value = withDelay(200,
      withSequence(
        withTiming(1.2, { duration: 200 }),
        withTiming(1, { duration: 150 }, () => {
          if (onAnimationComplete) {
            runOnJS(onAnimationComplete)();
          }
        })
      )
    );
  };

  /**
   * 重置动画值
   */
  const resetAnimation = () => {
    translateX.value = 0;
    opacity.value = 0;
    scale.value = 0;
    textScale.value = 0;
  };

  // 动画样式
  const animatedStyle = useAnimatedStyle(() => ({
    transform: [
      { translateX: translateX.value },
      { scale: scale.value }
    ],
    opacity: opacity.value,
  }));

  // 文字动画样式
  const textStyle = useAnimatedStyle(() => ({
    transform: [{ scale: textScale.value }],
  }));

  if (!isVisible) return null;

  return (
    <View style={styles.animationContainer}>
      <Animated.View style={[styles.errorIcon, animatedStyle]}>
        <Ionicons name="close-circle" size={80} color="#F44336" />
      </Animated.View>
      <Animated.View style={[styles.errorText, textStyle]}>
        <Text style={styles.errorTextContent}>再试试吧</Text>
      </Animated.View>
    </View>
  );
}

/**
 * 升级庆祝动画组件
 * 当用户升级时显示的特殊庆祝效果
 * 包含烟花效果和级别显示
 * @param {boolean} isVisible - 是否显示动画
 * @param {number} newLevel - 新等级
 * @param {Function} onAnimationComplete - 动画完成回调
 */
export function LevelUpAnimation({ isVisible, newLevel, onAnimationComplete }) {
  const scale = useSharedValue(0);
  const opacity = useSharedValue(0);
  const confettiScale = useSharedValue(0);
  const confettiOpacity = useSharedValue(0);
  const levelTextScale = useSharedValue(0);

  useEffect(() => {
    if (isVisible) {
      startLevelUpAnimation();
    } else {
      resetAnimation();
    }
  }, [isVisible]);

  /**
   * 开始升级动画序列
   * 多阶段的庆祝效果
   */
  const startLevelUpAnimation = () => {
    // 主图标动画
    scale.value = withSequence(
      withTiming(1.3, { duration: 300, easing: Easing.out(Easing.back(1.5)) }),
      withTiming(1, { duration: 200 })
    );

    opacity.value = withTiming(1, { duration: 300 });

    // 彩纸效果
    confettiScale.value = withDelay(200,
      withSequence(
        withTiming(1, { duration: 400 }),
        withTiming(0, { duration: 500 })
      )
    );

    confettiOpacity.value = withDelay(200,
      withSequence(
        withTiming(1, { duration: 400 }),
        withTiming(0, { duration: 500 })
      )
    );

    // 等级文字动画
    levelTextScale.value = withDelay(400,
      withSpring(1, { 
        damping: 8,
        stiffness: 200,
        mass: 1
      }, () => {
        if (onAnimationComplete) {
          runOnJS(onAnimationComplete)();
        }
      })
    );
  };

  /**
   * 重置动画值
   */
  const resetAnimation = () => {
    scale.value = 0;
    opacity.value = 0;
    confettiScale.value = 0;
    confettiOpacity.value = 0;
    levelTextScale.value = 0;
  };

  // 动画样式定义
  const mainStyle = useAnimatedStyle(() => ({
    transform: [{ scale: scale.value }],
    opacity: opacity.value,
  }));

  const confettiStyle = useAnimatedStyle(() => ({
    transform: [{ scale: confettiScale.value }],
    opacity: confettiOpacity.value,
  }));

  const levelTextStyle = useAnimatedStyle(() => ({
    transform: [{ scale: levelTextScale.value }],
  }));

  if (!isVisible) return null;

  return (
    <View style={styles.animationContainer}>
      {/* 彩纸效果 */}
      {[...Array(12)].map((_, index) => {
        const angle = (index * 30) * (Math.PI / 180);
        const radius = 80;
        const x = Math.cos(angle) * radius;
        const y = Math.sin(angle) * radius;
        const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD'];

        return (
          <Animated.View
            key={index}
            style={[
              styles.confetti,
              confettiStyle,
              {
                left: width / 2 + x - 5,
                top: height / 2 + y - 5,
                backgroundColor: colors[index % colors.length],
              }
            ]}
          />
        );
      })}

      {/* 皇冠图标 */}
      <Animated.View style={[styles.levelUpIcon, mainStyle]}>
        <Ionicons name="trophy" size={100} color="#FFD700" />
      </Animated.View>

      {/* 升级文字 */}
      <Animated.View style={[styles.levelUpText, levelTextStyle]}>
        <Text style={styles.levelUpTitle}>升级了！</Text>
        <Text style={styles.levelUpSubtitle}>现在是 {newLevel} 级</Text>
      </Animated.View>
    </View>
  );
}

/**
 * 脉冲动画组件
 * 用于强调重要元素的脉冲效果
 * @param {ReactNode} children - 子组件
 * @param {boolean} isActive - 是否激活动画
 */
export function PulseAnimation({ children, isActive = true }) {
  const scale = useSharedValue(1);

  useEffect(() => {
    if (isActive) {
      scale.value = withRepeat(
        withSequence(
          withTiming(1.05, { duration: 1000 }),
          withTiming(1, { duration: 1000 })
        ),
        -1, // 无限重复
        false
      );
    } else {
      scale.value = withTiming(1, { duration: 200 });
    }
  }, [isActive]);

  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{ scale: scale.value }],
  }));

  return (
    <Animated.View style={animatedStyle}>
      {children}
    </Animated.View>
  );
}

/**
 * 漂浮动画组件
 * 创建轻微的上下漂浮效果
 * @param {ReactNode} children - 子组件
 * @param {number} duration - 动画持续时间
 * @param {number} distance - 漂浮距离
 */
export function FloatingAnimation({ children, duration = 2000, distance = 5 }) {
  const translateY = useSharedValue(0);

  useEffect(() => {
    translateY.value = withRepeat(
      withSequence(
        withTiming(-distance, { duration: duration / 2, easing: Easing.inOut(Easing.sine) }),
        withTiming(distance, { duration: duration / 2, easing: Easing.inOut(Easing.sine) })
      ),
      -1,
      true
    );
  }, []);

  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{ translateY: translateY.value }],
  }));

  return (
    <Animated.View style={animatedStyle}>
      {children}
    </Animated.View>
  );
}

// 样式定义 - 简化版本
const styles = StyleSheet.create({
  animationContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.5)', // 半透明背景
    zIndex: 1000, // 确保在最顶层
  },
  mainIcon: {
    marginBottom: 20,
    alignItems: 'center',
    justifyContent: 'center',
  },
  successText: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  successTextContent: {
    fontSize: 32, // 增大字体，提高可见性
    fontWeight: 'bold',
    color: '#4CAF50',
    textAlign: 'center',
    textShadowColor: 'rgba(0,0,0,0.3)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 2,
  },
  errorIcon: {
    marginBottom: 20,
    alignItems: 'center',
    justifyContent: 'center',
  },
  errorText: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  errorTextContent: {
    fontSize: 32, // 增大字体，提高可见性
    fontWeight: 'bold',
    color: '#F44336',
    textAlign: 'center',
    textShadowColor: 'rgba(0,0,0,0.3)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 2,
  },
  levelUpIcon: {
    marginBottom: 30,
  },
  levelUpText: {
    alignItems: 'center',
  },
  levelUpTitle: {
    fontSize: 32,
    fontWeight: 'bold',
    color: '#FFD700',
    textAlign: 'center',
    marginBottom: 10,
  },
  levelUpSubtitle: {
    fontSize: 20,
    fontWeight: '600',
    color: '#FFF',
    textAlign: 'center',
  },
  confetti: {
    position: 'absolute',
    width: 10,
    height: 10,
    borderRadius: 5,
  },
});